package com.aliyun.messagemgt.application.service.Impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.messagemgt.common.dto.send.MsgMiddleResult;
import com.aliyun.messagemgt.common.dto.send.MsgRecordVO;
import com.aliyun.messagemgt.common.dto.send.Receiver;
import com.aliyun.messagemgt.application.service.UserMsgRestrain;
import com.aliyun.messagemgt.common.enums.PushResultEnum;
import com.aliyun.messagemgt.util.redis.Redis;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IDEA
 *
 * @author:zhangxingxing 0027012120
 * @date:2019/2/15
 * @time:16:21
 */
@Component
public class UserMsgRestrainImpl implements UserMsgRestrain {

    private static final String MODULE_NAME = "msg.restrain";

    private static final Integer EXPIRE_TIME = 60;

    /**
     * 1. 计算消息体的hash值
     * 2. 以用户维度插入redis 1min有效期  => a. 插入成功 则无重复消息 b. 插入失败则判断为重复消息
     *
     * @param msgRecordVoS
     */
    @Override
    public void restrain(List<MsgRecordVO> msgRecordVoS) {
        for (MsgRecordVO msgRecordVO : msgRecordVoS) {
            List<MsgMiddleResult> results = msgRecordVO.getResults();
            int msgHash = JSON.toJSONString(msgRecordVO.getContents()).hashCode();
            List<Receiver> receivers = msgRecordVO.getReceivers();
            // 无效用户
            List<Receiver> invalidUserIds = new ArrayList<>();
            // 有效用户
            List<Receiver> validUserIds = new ArrayList<>();
            for (Receiver receiver : receivers) {
                String receiverId = receiver.getReceiverId();
                String receiverMobilePhone = receiver.getReceiverMobilePhone();
                String receiverEmail = receiver.getReceiverEmail();
                String employeeCode = receiver.getEmployeeCode();
                String key = MODULE_NAME + "." +
                        msgRecordVO.getPushChannelId() +
                        msgRecordVO.getPushChannelType() +
                        receiverId + "." +
                        receiverMobilePhone + "." +
                        receiverEmail + "." +
                        employeeCode + "." +
                        msgHash;
                boolean notExsit = Redis.setTimer(key, EXPIRE_TIME);
                if (notExsit) {
                    validUserIds.add(receiver);
                } else {
                    invalidUserIds.add(receiver);
                }
            }
            if (!invalidUserIds.isEmpty()) {
                // 生成具体的接收者维度的状态信息
                MsgMiddleResult msgMiddleResult = new MsgMiddleResult()
                        .setReceivers(invalidUserIds)
                        .setPushResultCode(PushResultEnum.DUPLICATION_MSG_RESTRAIN.getErrorCode())
                        .setPushResultDescription(PushResultEnum.DUPLICATION_MSG_RESTRAIN.getDescription());
                results.add(msgMiddleResult);
            }
            msgRecordVO.setReceivers(validUserIds);
        }
    }
}
